import urllib2
import xmltodict
import logging
from django.conf import settings
from django.core.management import setup_environ
import mm.settings as msettings
setup_environ(msettings)
from mm.dashboard.models import Machine

class Poller:
    """
    Polls a list of servers running monit according to the various
    variables needed to grab the xml output from the monit servers.
    """

    urlprefix = 'http://'
    xmlurl = '_status?format=xml'
    servers = []
    services = {}
    platforms = {}
    serverstats = {}
    xml_dict = {}

    #LOGGING#
    logfile = settings.POLLER_LOGFILE
    logging.basicConfig(filename=logfile, format='[%(asctime)s]: %(message)s', level=logging.INFO, datefmt="%m/%d/%Y %I:%M:%S %p")
    logger = logging.getLogger()
    logger.propagate = True
    

    def get_xml(self):
        """
        run out to monit boxes and grab the xml data for status
        """
        self.xml_dict = {}
        for server in self.servers:
            cstring = '%s%s/%s' % (self.urlprefix, server, self.xmlurl)
            try:
                url = urllib2.urlopen(cstring)
            except:
                try:
                    obj = Machine.objects.filter(hostname=server)[0]
                except:
                    new_obj = Machine()
                    new_obj.hostname = server
                    new_obj.status = 'D'
                    new_obj.services = {}
                    new_obj.platform = {}
                    new_obj.server = {}
                    new_obj.save()
                    continue
                if obj.status != "D" and obj.status != "U" :
                    self.logger.error("[ERROR] -- Failed to open url: %s. Perhaps %s is down, or otherwise unreachable?" % (cstring, server))
                    obj = Machine.objects.filter(hostname=server)[0]
                    obj.status = 'D'
                    obj.save()
                continue
            xml = url.read()
            self.xml_dict['%s' % server] = xmltodict.parse(xml)
        
    def parsexml(self):
        """
        parse xml for storage per host.
        """
        for item in self.xml_dict:
            for i in self.xml_dict[item]['monit'].keys():
                if i == 'service':
                    for x in self.xml_dict[item]['monit'][i]:
                        try:
                            self.services[item][x['name']] = x
                        except KeyError:
                            self.services[item] = {}
                            self.services[item][x['name']] = x
                elif i == 'platform':
                    self.platforms[item] = self.xml_dict[item]['monit'][i]
                elif i == 'server':
                    self.serverstats[item] = self.xml_dict[item]['monit'][i]

    def stashit(self):
        """
        parse data structures, contruct new objects or update previously saved 
        records.  Fuck yea.
        """

        for server in self.servers:
            try:
                chkobj = Machine.objects.filter(hostname=server)[0]
            except IndexError:
                chkobj = None
            if chkobj:
                """
                we found a record that already exists, lets update that shit.
                """
                #self.logger.info("%s => %s" % (server, chkobj.status))
                chkobj.check_time()
                if chkobj.status == "D" and chkobj.hostname in self.xml_dict.keys():
                    #if we got here then the server is up and responding.
                    chkobj.status = 'O'
                try:
                    chkobj.services = self.services[server]
                    chkobj.server = self.serverstats[server]
                except KeyError:
                    continue
                try:
                    chkobj.platform = self.platforms[server]
                except KeyError:
                    pass
                chkobj.save()
                continue
            else:
                nm = Machine()
                nm.hostname = server
                nm.services = self.services[server]
                try:
                    nm.platform = self.platforms[server]
                except KeyError:
                    pass
                nm.server = self.serverstats[server]
                nm.save()
            
        
